const localStoragePlugin = (store) => {
  // 每次 Vuex 初始化时，尝试从 localStorage 加载数据
  const history = localStorage.getItem('history');
  if (history) {
    try {
      const parsedHistory = JSON.parse(history);
      if (Array.isArray(parsedHistory)) {
        store.commit('SET_HISTORY', parsedHistory);
      } else {
        console.warn('Invalid history data in localStorage, resetting to empty array');
        store.commit('SET_HISTORY', []); // 如果格式不对，则清空历史记录
      }
    } catch (e) {
      console.error('Failed to parse history from localStorage:', e);
      store.commit('SET_HISTORY', []); // 解析失败时清空
    }
  } else {
    store.commit('SET_HISTORY', []);
  }

  // 订阅 Vuex 的变化，每次修改历史时更新 localStorage
  store.subscribe((mutation, state) => {
    if (mutation.type === 'ADD_HISTORY' || mutation.type === 'REMOVE_HISTORY') {
      localStorage.setItem('history', JSON.stringify(state.history));
    }
  });
};

export default localStoragePlugin;
